import { login, getUserInfo, gerUserDetail } from '@/api/user'
import {
  getToken as getUserToken,
  setToken as setUserToken,
  removeToken,
  setTime
} from '@/utils/auth'

const state = {
  token: getUserToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, data) {
    setUserToken(data)
    setTime()
    state.token = data
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async getToken(store, data) {
    try {
      const res = await login(data)
      // console.log(res)
      store.commit('setToken', res)
    } catch (error) {
      console.log(error)
    }
  },

  async getUserInfo(store) {
    const info = await getUserInfo()
    const detail = await gerUserDetail(info.userId)
    const data = {
      ...info,
      ...detail
    }
    store.commit('setUserInfo', data)
  },

  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
